package com.spoto.oa.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.oreilly.servlet.MultipartRequest;
import com.spoto.oa.model.Customer;
import com.spoto.oa.service.CustomerServ;
import com.spoto.oa.service.impl.CustomerServImpl;
import com.spoto.oa.util.RandomFileRenamePolicy;

/**
 * 
 * @Project: OA
 * @Description: 客户管理模块
 * @Author: LinYiSong
 * @Vesion:
 * @Date: 2010-10-24~2010-10-24
 */
public class CustomerServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public CustomerServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String type = request.getParameter("op_type");
System.out.println(type);
		CustomerServ customerServ = new CustomerServImpl();
		Customer customer = new Customer();
		List<Customer> customers = null;
		List<Customer> conflictCustomers = new ArrayList<Customer>();
		if ("add".equals(type)) {
			// 从界面上取东西
			String name = request.getParameter("name");
			String company = request.getParameter("company");

			int level = Integer.parseInt(request.getParameter("level"));
			String mobile = request.getParameter("mobile");
			String address = request.getParameter("address");
			int qq = 0;
			if (!"".equals(request.getParameter("qq")))
				qq = Integer.parseInt(request.getParameter("qq"));
			String msn = request.getParameter("msn");
			String email = request.getParameter("email");
			String others = request.getParameter("others");
			// 创建者
			String creator = (String) request.getSession().getAttribute(
					"username");

			// 进行数据存储
			customer.setName(name);
			customer.setCompany(company);
			customer.setLevel(level);
			customer.setMobile(mobile);
			customer.setAddress(address);
			customer.setQq(qq);
			customer.setMsn(msn);
			customer.setEmail(email);
			customer.setOthers(others);
			customer.setCreator(creator);
			try {
				customerServ.addCustomer(customer);
			} catch (SQLException e) {
				e.printStackTrace();
			}

			customers = customerServ.getAllCustomers();
			request.setAttribute("customers", customers);
			request.getRequestDispatcher("/customer/welcome_customer.jsp?op_type=to_edit")
					.forward(request, response);

		} else if ("to_edit".equals(type)) {// 进入编辑
			customers = customerServ.getAllCustomers();
			request.setAttribute("customers", customers);
			request.getRequestDispatcher("/customer/welcome_customer.jsp")
					.forward(request, response);
		} else if ("to_update".equals(type)) {// 进行更新准备
			String name = request.getParameter("name");
			customer = customerServ.getCustomerByName(name);
			request.setAttribute("customer", customer);
			request.getRequestDispatcher("customer/update_customer.jsp")
					.forward(request, response);
		} else if ("update".equals(type)) {
			// 从界面上取东西
			String name = request.getParameter("name_hidden");
			String company = request.getParameter("company");
			String creator=request.getParameter("creator");
			System.out.println("creator"+creator);
			int level = Integer.parseInt(request.getParameter("level"));
			String mobile = request.getParameter("mobile");
			String address = request.getParameter("address");
			int qq = 0;
			if (!"".equals(request.getParameter("qq")))
				qq = Integer.parseInt(request.getParameter("qq"));
			String msn = request.getParameter("msn");
			String email = request.getParameter("email");
			String others = request.getParameter("others");

			// 进行数据存储
			customer.setName(name);
			customer.setCompany(company);
			customer.setLevel(level);
			customer.setMobile(mobile);
			customer.setAddress(address);
			customer.setQq(qq);
			customer.setMsn(msn);
			customer.setEmail(email);
			customer.setOthers(others);
			customer.setCreator(creator);
			customerServ.updateCustomer(customer);

			customers = customerServ.getAllCustomers();
			request.setAttribute("customers", customers);
			request.getRequestDispatcher("/customer/welcome_customer.jsp?op_type=to_edit")
					.forward(request, response);
		} else if ("delete".equals(type)) {
			String name = request.getParameter("name");
			customerServ.deleteCustomerByName(name);

			customers = customerServ.getAllCustomers();
			request.setAttribute("customers", customers);
			request.getRequestDispatcher("/customer/welcome_customer.jsp?op_type=to_edit")
					.forward(request, response);
		} else if ("multi_del".equals(type)) {
			String[] delName = request.getParameterValues("del-flag");
			for (int i = 0; i < delName.length; i++) {
				System.out.println(delName[i]);
				customerServ.deleteCustomerByName(delName[i]);
			}

			customers = customerServ.getAllCustomers();
			request.setAttribute("customers", customers);
			request.getRequestDispatcher("/customer/welcome_customer.jsp?op_type=to_edit")
					.forward(request, response);
		} else if ("search".equals(type)) {
			String searchType = request.getParameter("searchType");
			String infor = request.getParameter("infor");
			if ("".equals(infor)) {
				customers = customerServ.getAllCustomers();
				request.setAttribute("searchType", searchType);
				request.setAttribute("customers", customers);
				request.getRequestDispatcher("/customer/welcome_customer.jsp?op_type=to_edit")
						.forward(request, response);
			} else if ("客户姓名".equals(searchType)) {
				customers = customerServ.searchCustomersByName(infor);

				request.setAttribute("infor", infor);
				request.setAttribute("searchType", searchType);
				request.setAttribute("customers", customers);
				request.getRequestDispatcher("/customer/welcome_customer.jsp?op_type=to_edit")
						.forward(request, response);
			} else if ("公司名称".equals(searchType)) {
				customers = customerServ.searchCustomersByCompany(infor);

				request.setAttribute("infor", infor);
				request.setAttribute("searchType", searchType);
				request.setAttribute("customers", customers);
				request.getRequestDispatcher("/customer/welcome_customer.jsp?op_type=to_edit")
						.forward(request, response);
			} else if ("重要程度".equals(searchType)) {

				customers = customerServ.searchCustomersByLevel(Integer
						.parseInt(infor));

				request.setAttribute("infor", infor);
				request.setAttribute("searchType", searchType);
				request.setAttribute("customers", customers);
				request.getRequestDispatcher("/customer/welcome_customer.jsp?op_type=to_edit")
						.forward(request, response);
			} else if ("手机号码".equals(searchType)) {

				customers = customerServ.searchCustomersByMobile(Integer
						.parseInt(infor));

				request.setAttribute("infor", infor);
				request.setAttribute("searchType", searchType);
				request.setAttribute("customers", customers);
				request.getRequestDispatcher("/customer/welcome_customer.jsp?op_type=to_edit")
						.forward(request, response);
			} 
			
		}else if ("upload".equals(type)) {
			System.out.println("in upload");
			// 存绝对路径
			// String filePath = "C://upload";
			// 存相对路径
			String filePath = "G:";
			File uploadPath = new File(filePath);
			// 检查文件夹是否存在 不存在 创建一个
			if (!uploadPath.exists()) {
				uploadPath.mkdir();
			}
			// 文件最大容量 5M
			int fileMaxSize = 5 * 1024 * 1024;
			// 存放文件描述
			String[] fileDiscription = { null, null };
			// 文件名
			String fileName = null;
			// 上传文件数
			int fileCount = 0;
			// 重命名策略
			RandomFileRenamePolicy rfrp = new RandomFileRenamePolicy();
			// 上传文件
			MultipartRequest mulit = new MultipartRequest(request,
					filePath, fileMaxSize, "gbk", rfrp);
			filePath += rfrp.getFileName();

			// 将Excel文件读入数据库
			// 封装Employee
			InputStream inp = new FileInputStream(filePath);
			// InputStream inp = new FileInputStream("workbook.xlsx");

			HSSFWorkbook wb = new HSSFWorkbook(inp);// 可以看作是在虚拟下架构出一个workbook
			// 读取文件中的第一张表格
			HSSFSheet sheet = wb.getSheetAt(0);
			// 定义 row、cell
			HSSFRow row;
			// HSSFCell cell;
			String cell;
			// 循环输出表格中的内容
			
			for (int i = sheet.getFirstRowNum() + 1; i < sheet
					.getPhysicalNumberOfRows(); i++) {
				customer = new Customer();
				row = sheet.getRow(i);
				int j = row.getFirstCellNum();
				customer.setName(row.getCell(0 + j).toString());
				customer.setCompany(row.getCell(1 + j).toString());
				customer.setCreator(row.getCell(2 + j).toString());
				customer.setMobile(String.format("%.0f", row.getCell(3 + j)
						.getNumericCellValue()));
				customer.setAddress(row.getCell(4 + j).toString());// 根据jsp页面中的name属性取值
				customer.setEmail(row.getCell(5 + j).toString());
				customer.setQq((int) row.getCell(6 + j)
						.getNumericCellValue());
				customer.setMsn(row.getCell(7 + j).toString());
				customer.setLevel(Integer.parseInt(String.format("%.0f", row.getCell(8 + j)
						.getNumericCellValue())));
				customer.setOthers(row.getCell(9 + j).toString());
					try {
						customerServ.addCustomer(customer);
					} catch (SQLException e) {
						conflictCustomers.add(customer);
						customerServ.addCustomerConfict(customer);
					}
			}
			if (conflictCustomers.size() != 0) {
				System.out.println("conflict");
				request.setAttribute("customers", conflictCustomers);
				request.getRequestDispatcher("/customer/list_customer_conflict.jsp?op_type=conflict&kind=to_list")
						.forward(request, response);
			} else {
				customers = customerServ.getAllCustomers();
				request.setAttribute("customers", customers);
				request.getRequestDispatcher("/customer/welcome_customer.jsp?op_type=to_edit")
						.forward(request, response);
			}
		}else if("conflict".equals(type)){//处理导入员工数据时存在的冲突数据
			String kind=request.getParameter("kind");
			if("to_update".equals(kind)){
				String name = request.getParameter("name");
				customer=customerServ.getByNameConfict(name);
				customerServ.updateCustomer(customer);
				
				customerServ.deleteCustomerConfictByName(customer.getName());
				
				conflictCustomers=customerServ.getAllCustomersConfict();
				request.setAttribute("customers", conflictCustomers);
				request.getRequestDispatcher("/customer/list_customer_conflict.jsp?op_type=conflict&kind=to_list")
						.forward(request, response);
			}else if("delete".equals(kind)){
				String name = request.getParameter("name");
				customerServ.deleteCustomerConfictByName(name);
				
				conflictCustomers=customerServ.getAllCustomersConfict();
				request.setAttribute("customers", conflictCustomers);
				request.getRequestDispatcher("/customer/list_customer_conflict.jsp?kind=to_list")
						.forward(request, response);
			}else if("multi_del".equals(kind)){
				String[] delUserName = request.getParameterValues("del-flag");
				for (int i = 0; i < delUserName.length; i++) {
					customerServ.deleteCustomerConfictByName(delUserName[i]);
				}
				conflictCustomers=customerServ.getAllCustomersConfict();
				request.setAttribute("customers", conflictCustomers);
				request.getRequestDispatcher("/customer/list_customer_conflict.jsp?kind=to_list")
						.forward(request, response);
			}else if("to_list".equals(kind)){
				conflictCustomers=customerServ.getAllCustomersConfict();
				request.setAttribute("customers", conflictCustomers);
				request.getRequestDispatcher("/customer/list_customer_conflict.jsp?kind=to_list")
						.forward(request, response);
			}
		}else if("valicate".equals(type)){//进行异步验证
			String kind=request.getParameter("kind");
			System.out.println(kind);
			if("name".equals(kind)){
				String name=request.getParameter("name");
				PrintWriter out=response.getWriter();
				if(null!=customerServ.getCustomerByName(name)){
					System.out.println("have");
					out.write("false");
				}else{
					out.write("true");
				}
			}
		}
		

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
